package com.fz.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * Created by webrx on 2017-09-05.
 */
@Controller
public class Upload {
//    @RequestMapping("/upload.do") @ResponseBody
//    public void upfile(@RequestParam("ff") CommonsMultipartFile cmf, String name, PrintWriter out) throws IOException {
//        System.out.println(name);
//        String filename = cmf.getOriginalFilename();
//        cmf.transferTo(new File("d:/",filename));
//        out.print(String.format("文件名:%s字节<br>",filename));
//        out.print(String.format("表单名:%s字节<br>",cmf.getName()));
//        out.print(String.format("文件大小写:%d字节<br>",cmf.getSize()));
//        out.print(cmf.getContentType());
//    }

    @RequestMapping("/upload.do")
    public ModelAndView upfile(@RequestParam("ff") CommonsMultipartFile cmf, String name, HttpServletRequest req) throws IOException {
        ModelAndView mv = new ModelAndView("upf");  //WEB-INF/views/upf.jsp
        if(cmf.isEmpty()){
            mv.addObject("info","文件上传失败，没有选择文件");
            //mv.setViewName("upf-error.jsp");
        }else {
            //建立目录

            String s = new SimpleDateFormat("yyMM").format(new Date());  //1709   /upload/1709/
            String path = "/upload/"+s;
            String p = req.getServletContext().getRealPath(path);
            File ff = new File(p);
            if(!ff.exists()){
                ff.mkdirs();
            }

            String nn = cmf.getOriginalFilename();

            cmf.transferTo(new File(p,nn));




            mv.addObject("name", cmf.getOriginalFilename());
            mv.addObject("size", cmf.getSize());
            mv.addObject("contenttype", cmf.getContentType());
            mv.addObject("formname", cmf.getName());
            //mv.setViewName("upf-success.jsp");
        }
       return mv;
    }

    @RequestMapping("/ups") @ResponseBody
    public void ups(@RequestParam("fs") CommonsMultipartFile[] fs) throws IOException {
        System.out.println(fs.length);
        for(CommonsMultipartFile f : fs){
            if(f.isEmpty()) continue;
            f.transferTo(new File("d:/",f.getOriginalFilename()));
        }
    }
}
